<?php
/**
 * 
 * @author Administrator
 *
 */

class ModRole extends Model {

    private $table = 'tblrole';

    // 表名
    public function tableName(){
        return $this->table;
    }

    public static function model($className=__CLASS__){
        return parent::model($className);
    }

    public function getDbConnection(){
        return Yii::app()->dbAuth;
    }
    
    
    public function page($params){
    	$table = $this->table;
    	$where = ' WHERE 1';
    	$args = array();

    
    	if(!empty($params['RoleName'])){
    		$where .= " AND RoleName like :RoleName ";
    		$args['RoleName'] = '%'.$params['RoleName'].'%';
    	}
    	
    	if(!empty($params['identity'])){
    		$where .= " AND identity = :identity ";
    		$args['identity'] = $params['identity'];
    	}
    	
    	if(!empty($params['AddBy'])){
    		$where .= ' AND AddBy = :AddBy ';
    		$args[':AddBy'] = $params['AddBy'];
    	}
    	 
    	$c_sql = "select count(1) as cnt from {$table} {$where}";
    	$c_result = $this->getDbConnection()->query($c_sql, $args);
    	$count = isset($c_result[0]['cnt']) ? $c_result[0]['cnt'] : 0;
    
    	$order  = self::getOrder($params['order']);
    	$limit  = PubFunc::getLimit($params['length'], $params['page']);
    	$fields = "*";
    	$sql = "SELECT {$fields} FROM {$table} {$where} {$order} {$limit}";
    	$data = $this->getDbConnection()->query($sql, $args);
    	$result = array('count'=>$count,'data'=>$data);
    	return $result;
    }
    
    public function select($params=array()){
    	// 子查询，筛选用户的类型和系统ID
    	$where = ' WHERE 1';
    	$args = array();
    
    	if(!empty($params['RoleName'])){
    		$where .= ' AND RoleName LIKE :RoleName ';
    		$args[':RoleName'] = "%{$params['RoleName']}%";
    	}
    	
    	if(!empty($params['AddBy'])){
    		$where .= ' AND AddBy = :AddBy ';
    		$args[':AddBy'] = $params['AddBy'];
    	}
    
    	$sql = "SELECT RoleID,RoleName
    	FROM {$this->table} {$where}";
    
    	$result = $this->getDbConnection()->getAll($sql, $args);
    
    	return $result;
    }
    
    
    public static function getOrder($order){
    	if(PubFunc::checkEmpty($order, array(0, 1))) return '';
    	if(!in_array($order[1], array('asc', 'desc'))){
    		$sort = 'asc';
    	}else{
    		$sort = $order[1];
    	}
    	return " ORDER BY {$order[0]} {$sort} ";
    }
    
    /**
     * 去重
     * @param number $id  主键id
     * @param unknown $field 检查是否重复的字段名
     * @param unknown $val 检查是否重复的值
     * @return number
     */
    public function repeat($id,$field,$val){
    	$sql = "SELECT count(1) as cnt FROM {$this->table} where RoleID != {$id} and {$field} = '{$val}'";
    	$c_result = $this->getDbConnection()->getAll($sql, $args);
    	$count = isset($c_result[0]['cnt']) ? $c_result[0]['cnt'] : 0;
    	return $count;
    }

   
} 